文章目录
  1. 1. 前言
  2. 2. 介绍
  3. 3. UIAlertAction
  4. 4. 展示

前言

UIAlertController是iOS 8之后提供的一个继承自UIViewController的视图控制器,主要是修改了UIAlertViewUIActionSheet的显示以及处理逻辑,摒弃了旧形式,提供了更加强大的操作方法。它将UIAlertViewUIActionSheet整合到一起,并且添加了对block的支持。本篇文章我们就具体讲一下UIAlertControlelr的使用。

介绍

UIAlertController作为UIViewController的子类,因此显示工作需要我们提供,而不像之前的UIAlertViewUIActionSheet单独作为一个视图,提供了显示的方法。UIAlertController提供了俩种形式:

1
2
UIAlertControllerStyleActionSheet
UIAlertControllerStyleAlert

上面这俩种形式,就应对了我们之前使用的UIAlertViewUIActionSheet

UIAlertAction

UIAlertController中,一个事件就叫一个UIAlertAction的实例,这里面就是添加对block机制的支持。而UIAlertController就是通过添加UIAlertAction的实例来添加操作的。下面是添加方法:

1
- (void)addAction:(UIAlertAction *)action;

而每一个UIAlertAction代表了一个操作,比如Cancel操作等。一个UIAlertActiontitle,style属性,style属性是UIAlertControllerStyle类型的,这决定着是添加一个UIAlertView的操作,还是UIActionSheet的操作。实例初始化方法如下:

1
+ (instancetype)actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction *action))handler;

展示

谈到UIAlertController的展示之前,我们必须先说一下UIPresentationControllerUIAlertController与传统的UIAlertView,UIActionSheet最大不同之处在于,在大宽屏幕上是以UIPopoverViewController来显示的,首先推荐一篇比较全面的博客:iOS8新特性 UIPresentationController

UIPresentationController主要是为开发者不用再手动计算视图的位置以及适配各种分辨率的屏幕而设计。在iOS 8以后,系统会自动匹配各种宽度的屏幕,而UIPresentationController就是提供了适配的一些操作。在iPad等大宽屏幕设备上,如果使用了UIAlertController,那么系统就会以popoverPresentationController的形式将视图弹出,所以此时,我们必须设置popoverPresentationControllersourceViewsourceRect或者是barButtonItem,这样系统才会根据我们的设置弹出popover视图。使用方法如下:

1
2
3
4
5
6
7
8
9

UIPopoverPresentationController *popover = alertController.popoverPresentationController;
if (popover) {
popover.barButtonItem = self.navigationItem.rightBarButtonItem;
}

[self presentViewController:alertController animated:YEScompletion:^{

}];

文章目录
  1. 1. 前言
  2. 2. 介绍
  3. 3. UIAlertAction
  4. 4. 展示